/**
 * @file
 * @brief 应用程序入口
 * @author
 * + 隐星魂 (Roy Sun) <xwos@xwos.tech>
 * @copyright
 * + Copyright © 2015 xwos.tech, All Rights Reserved.
 * > Licensed under the Apache License, Version 2.0 (the "License");
 * > you may not use this file except in compliance with the License.
 * > You may obtain a copy of the License at
 * >
 * >         http://www.apache.org/licenses/LICENSE-2.0
 * >
 * > Unless required by applicable law or agreed to in writing, software
 * > distributed under the License is distributed on an "AS IS" BASIS,
 * > WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * > See the License for the specific language governing permissions and
 * > limitations under the License.
 */

#include "board/std.h"
#include <xwos/osal/thd.h>
#include "RTD/xwds/device.h"
#include "App/kl15.h"

#define MAIN_THD_PRIORITY XWOS_SKD_PRIORITY_DROP(XWOS_SKD_PRIORITY_RT_MAX, 0)

xwer_t main_task(void * arg);

__xwcc_alignl1cache xwu8_t main_thd_stack[4096] = {0};
struct xwos_thd main_thd;
xwos_thd_d main_thdd;

xwer_t xwos_main(void)
{
        xwer_t rc;
        struct xwos_thd_attr attr;

        xwos_thd_attr_init(&attr);
        attr.name = "main.thd";
        attr.stack = (xwstk_t *)main_thd_stack;
        attr.stack_size = sizeof(main_thd_stack);
        attr.priority = MAIN_THD_PRIORITY;
        attr.detached = true;
        attr.privileged = true;
        rc = xwos_thd_init(&main_thd, &main_thdd,
                           &attr,
                           main_task,
                           NULL);
        if (rc < 0) {
                goto err_thd_init;
        }

        rc = xwos_skd_start_lc();
        if (rc < 0) {
                goto err_skd_start_lc;
        }
        return XWOK;

err_skd_start_lc:
        XWOS_BUG();
err_thd_init:
        XWOS_BUG();
        return rc;
}

__xwcc_alignl1cache xwu8_t txdata[] = "S32K3XWOS\n";
__xwcc_alignl1cache xwu8_t rxdata[8];
xwer_t main_task(void * arg)
{
        xwer_t rc;
        xwsz_t txsz;
        xwsz_t rxsz;

        XWOS_UNUSED(arg);
        kl15_start_detection();
        while (!xwos_cthd_shld_stop()) {
                if (xwos_cthd_shld_frz()) {
                        xwos_cthd_freeze();
                }
                xwos_cthd_sleep(xwtm_s(1));
                txsz = sizeof(txdata);
                rc = xwds_uartc_tx(&mcalxwds_uart2, txdata, &txsz, XWTM_MAX);
                rxsz = sizeof(rxdata);
                rc = xwds_uartc_try_rx(&mcalxwds_uart2, rxdata, &rxsz);
                if (XWOK == rc) {
                        rc = xwds_uartc_tx(&mcalxwds_uart2, rxdata, &rxsz, XWTM_MAX);
                        XWOS_BUG_ON(rc < 0);
                }
        }
        return XWOK;
}
